<template>
  <div class="simple-timeline">
    <div class="timeline-header">
      <h2>专利时间脉络 - 简化版</h2>
      <div class="header-actions">
        <Button type="primary" @click="loadData" :loading="loading">
          加载数据
        </Button>
        <Button @click="testConnection">
          测试连接
        </Button>
      </div>
    </div>

    <!-- 连接状态 -->
    <div class="connection-status">
      <Alert 
        v-if="connectionStatus" 
        :type="connectionStatus.type" 
        :message="connectionStatus.message"
        show-icon
      />
    </div>

    <!-- 数据统计 -->
    <div v-if="statistics" class="statistics">
      <Row :gutter="16">
        <Col :span="6">
          <Card>
            <Statistic title="总专利数" :value="statistics.totalPatents" />
          </Card>
        </Col>
        <Col :span="6">
          <Card>
            <Statistic title="申请事件" :value="statistics.applicationCount" />
          </Card>
        </Col>
        <Col :span="6">
          <Card>
            <Statistic title="公布事件" :value="statistics.publicationCount" />
          </Card>
        </Col>
        <Col :span="6">
          <Card>
            <Statistic title="总事件数" :value="statistics.totalEvents" />
          </Card>
        </Col>
      </Row>
    </div>

    <!-- 时间脉络列表 -->
    <div v-if="timelineData.length > 0" class="timeline-list">
      <Card title="时间脉络事件">
        <div class="event-list">
          <div 
            v-for="(event, index) in timelineData.slice(0, 20)" 
            :key="index"
            class="event-item"
          >
            <div class="event-date">{{ formatDate(event.date) }}</div>
            <div class="event-type" :class="`type-${event.type}`">
              {{ event.type }}
            </div>
            <div class="event-description">{{ event.description }}</div>
            <div class="event-meta">
              <Tag v-if="event.inventor">{{ event.inventor }}</Tag>
              <Tag v-if="event.institution">{{ event.institution }}</Tag>
            </div>
          </div>
        </div>
      </Card>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <Spin size="large" />
      <p>正在加载数据...</p>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && timelineData.length === 0" class="empty">
      <Empty description="暂无数据">
        <Button type="primary" @click="loadData">重新加载</Button>
      </Empty>
    </div>

    <!-- 错误信息 -->
    <div v-if="errorMessage" class="error">
      <Alert type="error" :message="errorMessage" show-icon />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Button, Alert, Row, Col, Card, Statistic, Tag, Spin, Empty, message } from 'ant-design-vue';
import { getPatentTimeline } from './TimeLine.api';

const loading = ref(false);
const timelineData = ref<any[]>([]);
const statistics = ref<any>(null);
const connectionStatus = ref<any>(null);
const errorMessage = ref('');

// 格式化日期
const formatDate = (dateStr: string) => {
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN');
  } catch (e) {
    return dateStr;
  }
};

// 测试连接（使用专利列表API）
const testConnectionAsync = async () => {
  try {
    connectionStatus.value = {
      type: 'info',
      message: '正在测试连接...'
    };
    
    console.log('开始测试专利数据连接...');
    const result = await getPatentTimeline();
    console.log('测试结果:', result);
    
    if (result.success) {
      connectionStatus.value = {
        type: 'success',
        message: `连接成功！数据库中共有 ${result.result.statistics.totalPatents} 条专利数据，${result.result.statistics.totalEvents} 个时间节点`
      };
      message.success('专利数据连接正常');
    } else {
      connectionStatus.value = {
        type: 'error',
        message: '连接失败：' + (result.message || '未知错误')
      };
      message.error('专利数据连接失败');
    }
  } catch (error) {
    console.error('连接测试失败:', error);
    connectionStatus.value = {
      type: 'error',
      message: '连接测试失败：' + (error as Error).message
    };
    message.error('连接测试失败：' + (error as Error).message);
  }
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  errorMessage.value = '';
  
  try {
    console.log('开始加载时间脉络数据...');
    const result = await getPatentTimeline();
    console.log('API响应:', result);
    
    if (result.success && result.result) {
      timelineData.value = result.result.timelineData || [];
      statistics.value = result.result.statistics || null;
      
      message.success(`数据加载成功，共 ${timelineData.value.length} 个事件`);
      console.log('时间脉络数据:', timelineData.value);
      console.log('统计信息:', statistics.value);
    } else {
      errorMessage.value = result.message || '数据加载失败';
      message.error(errorMessage.value);
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    errorMessage.value = '网络请求失败：' + (error as Error).message;
    message.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  console.log('SimpleTimeline 组件已挂载');
  testConnectionAsync();
});
</script>

<style lang="less" scoped>
.simple-timeline {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.timeline-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  h2 {
    margin: 0;
    color: #262626;
  }
}

.header-actions {
  display: flex;
  gap: 8px;
}

.connection-status {
  margin-bottom: 24px;
}

.statistics {
  margin-bottom: 24px;
  
  .ant-card {
    text-align: center;
  }
}

.timeline-list {
  margin-bottom: 24px;
}

.event-list {
  max-height: 600px;
  overflow-y: auto;
}

.event-item {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 16px;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:hover {
    background: #fafafa;
  }
}

.event-date {
  min-width: 100px;
  font-weight: 500;
  color: #1890ff;
}

.event-type {
  min-width: 60px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  
  &.type-申请 {
    background: #e6f7ff;
    color: #1890ff;
  }
  
  &.type-公布 {
    background: #f6ffed;
    color: #52c41a;
  }
}

.event-description {
  flex: 1;
  color: #595959;
}

.event-meta {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.loading, .empty, .error {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  margin-bottom: 24px;
}

.loading p {
  margin-top: 16px;
  color: #666;
}

// 响应式设计
@media (max-width: 768px) {
  .timeline-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .event-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .event-date, .event-type {
    min-width: auto;
  }
}
</style>
